<template>
  <div>
    <div class="flex-col" @click="handleClick">
      <div
        class="flex-col justify-start section_5"
        :style="{
          backgroundImage: `url('${backgroundImage}')`,
        }"
      >
        <div class="info-overlay" v-if="dataItem.money">
          <div class="price-tag">
            <span class="font_3">{{ dataItem.money || 0 }}r/题</span>
          </div>
          <div v-if="dataItem.totalPeople" class="people-tag">
            <i class="el-icon-user"></i>
            <span>{{ dataItem.totalParticipants }}人</span>
          </div>
        </div>
        <!-- 添加帖子删除按钮 -->
        <div
          v-if="dataItem.type === 'activity' && (isCreator || isAdmin)"
          class="delete-button"
          @click.stop="showDeleteConfirm"
        >
          <i class="el-icon-delete"></i>
        </div>
        <!-- 添加任务删除按钮 -->
        <div
          v-if="dataItem.type !== 'activity' && isAdmin"
          class="delete-job-button"
          @click.stop="showDeleteConfirm"
        >
          <i class="el-icon-delete"></i>
        </div>
        <!-- 添加任务终止按钮 -->
        <div
          v-if="dataItem.type !== 'activity' && isAdmin"
          class="terminate-button"
          @click.stop="showTerminateConfirm"
        >
          <i class="el-icon-video-pause"></i>
        </div>
        <!-- 添加编辑按钮 -->
        <div
          v-if="dataItem.type !== 'activity' && (isCreator || isAdmin)"
          class="edit-button"
          @click.stop="handleEdit"
        >
          <i class="el-icon-edit"></i>
        </div>
      </div>

      <div class="flex-col section_6">
        <div class="title-row">
          <span class="font_4 text_9">{{ dataItem.title || "默认标题" }}</span>
          <span v-if="dataItem.createdAt" class="date-tag">
            {{ formatDate(dataItem.createdAt) }}
          </span>
        </div>

        <div
          v-if="dataItem.endTime && dataItem.type !== 'activity'"
          class="deadline-info"
        >
          <i class="el-icon-time"></i>
          <span>截止时间: {{ formatDate(dataItem.endTime) }}</span>
        </div>

        <div class="tag_span">
          <span
            v-for="(tag, index) in processedTags || ['暂无']"
            :key="index"
            class="font_5"
          >
            {{ tag }}
          </span>
        </div>

        <div class="job-details">
          <div
            class="detail-item"
            v-if="dataItem.groupCount && dataItem.groupSize"
          >
            <i class="el-icon-s-operation"></i>
            <span
              >{{ dataItem.groupCount }}组 × {{ dataItem.groupSize }}人</span
            >
          </div>

          <div class="detail-item" v-if="dataItem.enableAI">
            <i class="el-icon-cpu"></i>
            <span>
              {{ getAIModeText }}
              <el-tag
                size="mini"
                :type="dataItem.useMirror ? 'warning' : 'info'"
                class="ai-tag"
              >
                {{ dataItem.useMirror ? "镜像" : "普通" }}
              </el-tag>
            </span>
          </div>

          <!-- 添加发帖人信息显示 -->
          <div
            class="detail-item"
            v-if="dataItem.type === 'activity' && dataItem.createdBy"
          >
            <i class="el-icon-user"></i>
            <span>{{ userName || "加载中..." }}</span>
            <span class="post-time">{{ formatDate(dataItem.created_at) }}</span>
          </div>

          <!-- 添加点赞信息 -->
          <div
            class="detail-item like-item"
            v-if="dataItem.type === 'activity'"
            @click.stop="handleLike"
          >
            <i
              class="el-icon-thumb like-icon"
              :class="{
                'el-icon-thumb-up': dataItem.isLiked,
                liked: dataItem.isLiked,
              }"
            ></i>
            <span class="like-count">{{ dataItem.likesCount }}</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 添加确认对话框 -->
    <el-dialog
      title="确认删除"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <span>确定要删除这个{{ dataItem.type === 'activity' ? '活动' : '任务' }}吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleDelete">确定</el-button>
      </span>
    </el-dialog>

    <!-- 添加终止确认对话框 -->
    <el-dialog
      title="确认终止"
      :visible.sync="terminateDialogVisible"
      width="30%"
      :before-close="handleTerminateClose"
    >
      <span>确定要终止这个任务吗？终止后将无法恢复。</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="terminateDialogVisible = false">取消</el-button>
        <el-button type="warning" @click="handleTerminate">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
import defaultImage from "@/assets/images/default-king.png";
import {
  deleteActivity,
  deleteJob,
  queryUserById,
  toggleActivityLike,
  terminateJob,
} from "@/api/api";
import apiClient from "@/api/api";
import { getRole } from "@/api/auth";

// SECTION 常量定义
const DEFAULT_TAG_ORIGIN = "暂无";
const DATE_PAD_LENGTH_ORIGIN = 2;

export default {
  name: "CommonCard",

  props: {
    dataItem: {
      type: Object,
      required: true,
    },
  },

  data() {
    return {
      backgroundImage: "",
      dialogVisible: false,
      terminateDialogVisible: false,
      userName: "", // 添加用户名状态
      userInfo: null, // 存储当前登录用户信息
      isLiked: false, // 是否已点赞
      likeCount: 0, // 点赞数量
    };
  },

  // SECTION 计算属性
  computed: {
    isAdmin() {
      return getRole() === "admin";
    },
    isCreator() {
      return this.userInfo && this.dataItem.createdBy === this.userInfo.userId;
    },
    ...mapGetters(["toDetail"]),

    // NOTE: 处理标签显示，支持字符串和数组两种格式
    processedTags() {
      if (!this.dataItem.tags) return [DEFAULT_TAG_ORIGIN];
      return typeof this.dataItem.tags === "string"
        ? this.dataItem.tags.split(",").map((tag) => tag.trim())
        : this.dataItem.tags;
    },

    // NOTE: 根据AI模式返回对应的显示文本
    getAIModeText() {
      if (!this.dataItem.enableAI) return "";
      return this.dataItem.aiMode === "internal" ? "内置AI" : "外置AI";
    },
  },

  // SECTION 方法定义
  methods: {
    // 获取用户信息
    async fetchUserInfo() {
      try {
        const response = await apiClient.get("/user/info");
        this.userInfo = response.data;
      } catch (error) {
        console.error("获取用户信息失败:", error);
        this.userInfo = null;
      }
    },

    // NOTE: 图片处理相关方法
    getImageUrl() {
      if (this.dataItem.imageSrc && this.dataItem.imageSrc.trim()) {
        return encodeURI(this.dataItem.imageSrc.trim());
      }
      return defaultImage;
    },

    // 显示删除确认对话框
    showDeleteConfirm() {
      this.dialogVisible = true;
    },

    // 处理对话框关闭
    handleClose() {
      this.dialogVisible = false;
    },

    // 显示终止确认对话框
    showTerminateConfirm() {
      this.terminateDialogVisible = true;
    },

    // 处理终止对话框关闭
    handleTerminateClose() {
      this.terminateDialogVisible = false;
    },

    // 处理终止确认
    async handleTerminate() {
      try {
        await terminateJob(this.dataItem.jobId);
        this.$message.success("任务已终止");
        this.terminateDialogVisible = false;
        // 刷新页面或更新状态
        this.$emit("job-terminated", this.dataItem.jobId);
      } catch (error) {
        console.error("终止失败:", error);
        this.$message.error("终止失败，请重试");
      }
    },

    // 处理删除确认
    async handleDelete() {
      try {
        if (this.dataItem.type === 'activity') {
          await deleteActivity(this.dataItem.activityId);
          this.$emit("activity-deleted", this.dataItem.activityId);
        } else {
          console.log("删除任务", this.dataItem.jobId);
          await deleteJob(this.dataItem.jobId);
          this.$emit("job-deleted", this.dataItem.jobId);
        }
        this.$message.success("删除成功，请重新刷新页面...");
        this.dialogVisible = false;
      } catch (error) {
        console.error("删除失败:", error);
        this.$message.error("删除失败，请重试");
      }
    },

    loadBackgroundImage() {
      const url = this.getImageUrl().replace("https://", "http://");
      const img = new Image();

      this.backgroundImage = defaultImage;

      img.onload = () => {
        this.backgroundImage = url;
      };

      img.onerror = () => {
        console.error("Image load failed:", url);
        this.backgroundImage = defaultImage;
      };

      img.src = url;
    },

    handleAvatarError(e) {
      e.target.src = defaultImage;
    },

    // NOTE: 路由跳转相关方法
    ...mapActions(["updateToDetail"]),

    handleClick() {
      console.log("dataItem", this.dataItem);
      const routeConfig = this.getRouteConfig();
      if (routeConfig) {
        this.handleRouteNavigation(routeConfig);
      }
    },

    getRouteConfig() {
      const { type, activityId, jobId } = this.dataItem;
      console.log("type", type);
      const configs = {
        idea: { name: "post_detail" },
        challenge: { name: "challenge_detail", query: { id: activityId } },
        activity: { name: "activity_detail", query: { id: activityId } },
        job: { name: "job_detail", params: { id: jobId } },
        edit_job: {
          name: "edit_job",
          params: { id: jobId, jobInfo: this.dataItem },
        },
      };
      console.log("configs", configs);

      // 修正逻辑：
      // 1. 如果 type 是 'job'，返回任务详情配置
      // 2. 如果 type 存在，返回对应类型的配置
      // 3. 如果 type 不存在但有 jobId，说明是任务，返回任务详情配置
      // 4. 默认返回 null
      if (type === "job") {
        return configs.job;
      } else if (type && configs[type]) {
        return configs[type];
      } else if (jobId) {
        return configs.job;
      }
      return null;
    },

    handleRouteNavigation(routeConfig) {
      if (this.dataItem.type !== "idea" && this.dataItem.activityId) {
        localStorage.setItem("activityId", this.dataItem.activityId);
      }
      console.log("用户点击了跳转");
      this.$router.push(routeConfig);
    },

    handleEdit() {
      if (this.dataItem && this.dataItem.jobId) {
        this.$router.push({
          name: "edit_job",
          query: { id: this.dataItem.jobId },
        });
      }
    },

    clickButton() {
      this.$router.push({ name: "upload_challenge" });
    },

    // NOTE: 日期格式化方法
    formatDate(dateString) {
      if (!dateString) return "";
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
        DATE_PAD_LENGTH_ORIGIN,
        "0"
      )}-${String(date.getDate()).padStart(DATE_PAD_LENGTH_ORIGIN, "0")}`;
    },

    // 加载点赞数据
    loadLikeData(activity) {
      if (!activity) {
        console.warn("loadLikeData: 活动数据为空");
        return;
      }

      console.log("加载点赞数据，活动ID:", activity.id, "活动:", activity);

      // 设置点赞状态 - 兼容多种可能的字段名
      // 优先使用isLiked字段，其次使用liked字段
      this.dataItem.isLiked =
        activity.isLiked !== undefined
          ? activity.isLiked
          : activity.liked !== undefined
          ? activity.liked
          : false;

      // 设置点赞数量 - 兼容多种可能的字段名
      // 优先使用新的likesCount字段，其次是likeCount字段，再次使用likedCount字段，再次使用count字段
      this.dataItem.likeCount =
        activity.likesCount !== undefined
          ? activity.likesCount
          : activity.likeCount !== undefined
          ? activity.likeCount
          : activity.likedCount !== undefined
          ? activity.likedCount
          : activity.count !== undefined
          ? activity.count
          : 0;

      console.log("CommonCard解析的点赞信息:", {
        activityId: activity.id,
        isLiked: this.dataItem.isLiked,
        likeCount: this.dataItem.likeCount,
      });
      console.log("原始点赞数据:", {
        isLiked: activity.isLiked,
        liked: activity.liked,
        likesCount: activity.likesCount,
        likeCount: activity.likeCount,
        likedCount: activity.likedCount,
        count: activity.count,
      });
    },

    // 处理点赞操作
    async handleLike(event) {
      // 防止事件冒泡，避免触发卡片的点击事件
      if (event) {
        event.stopPropagation();
      }

      try {
        // 获取活动ID - 优先使用id字段，其次使用activityId字段
        const activityId = this.dataItem.id || this.dataItem.activityId;
        if (!activityId) {
          console.error("handleLike: 无法获取活动ID", this.dataItem);
          this.$message.error("操作失败");
          return;
        }

        console.log("发起点赞请求，活动ID:", activityId);

        // 先更新UI状态，提供即时反馈
        const oldLiked = this.dataItem.isLiked || false;
        const oldCount =
          this.dataItem.likesCount || this.dataItem.likeCount || 0;

        // 乐观更新UI
        this.dataItem.isLiked = !oldLiked;
        this.dataItem.liked = !oldLiked;
        this.dataItem.likesCount = oldLiked
          ? Math.max(0, oldCount - 1)
          : oldCount + 1;
        this.dataItem.likeCount = this.dataItem.likesCount;

        // 调用API
        const result = await toggleActivityLike(activityId);
        console.log("点赞操作结果:", result);

        if (!result) {
          console.error("点赞操作返回为空");
          // 恢复原始状态
          this.dataItem.isLiked = oldLiked;
          this.dataItem.liked = oldLiked;
          this.dataItem.likesCount = oldCount;
          this.dataItem.likeCount = oldCount;
          this.isLiked = oldLiked;
          this.likeCount = oldCount;
          this.$message.error("操作失败");
          return;
        }

        // 根据API返回更新实际状态
        const newLikedStatus =
          result.liked !== undefined
            ? result.liked
            : result.isLiked !== undefined
            ? result.isLiked
            : !oldLiked;

        const newLikeCount =
          result.likesCount !== undefined
            ? result.likesCount
            : result.count !== undefined
            ? result.count
            : result.likeCount !== undefined
            ? result.likeCount
            : result.likedCount !== undefined
            ? result.likedCount
            : newLikedStatus
            ? oldCount + 1
            : Math.max(0, oldCount - 1);

        // 更新数据
        this.dataItem.isLiked = newLikedStatus;
        this.dataItem.liked = newLikedStatus;
        this.dataItem.likesCount = newLikeCount;
        this.dataItem.likeCount = newLikeCount;

        // 同步更新组件状态（如果有需要）
        this.isLiked = newLikedStatus;
        this.likeCount = newLikeCount;

        // 缓存点赞状态
        localStorage.setItem(
          `activity_${activityId}_liked`,
          this.dataItem.isLiked.toString()
        );

        // 用户反馈
        this.$message.success(
          this.dataItem.isLiked ? "点赞成功" : "已取消点赞"
        );
      } catch (error) {
        console.error("点赞操作失败:", error);
        // 恢复原始状态
        this.dataItem.isLiked = oldLiked;
        this.dataItem.liked = oldLiked;
        this.dataItem.likesCount = oldCount;
        this.dataItem.likeCount = oldCount;
        this.isLiked = oldLiked;
        this.likeCount = oldCount;
        this.$message.error("操作失败");
      }
    },
  },

  // SECTION 生命周期钩子
  mounted() {
    this.loadBackgroundImage();
    this.fetchUserInfo();
    if (this.dataItem.type === "activity") {
      this.loadLikeData(this.dataItem);
    }
  },

  // SECTION 侦听器
  watch: {
    "dataItem.createdBy": {
      immediate: true,
      async handler(newUserId) {
        if (newUserId) {
          try {
            const userData = await queryUserById(newUserId);
            this.userName = userData.username;
          } catch (error) {
            console.error("获取用户信息失败:", error);
            this.userName = "未知用户";
          }
        }
      },
    },
    "dataItem.imageSrc": {
      handler() {
        this.loadBackgroundImage();
      },
      immediate: true,
    },
  },
};
</script>
<style scoped>
.flex-col {
  font-family: Cera-Bold, sans-serif;
  display: flex;
  flex-direction: column;
  border-radius: 8px; /* 圆角 */
  transition: transform 0.3s ease, box-shadow 0.3s ease; /* 动画效果 */
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); /* 默认阴影 */
  width: 300px; /* 添加固定宽度 */
  overflow: hidden; /* 防止内容溢出 */
}

.flex-col:hover {
  /* transform: translateY(-10px); 悬浮时整体上移 */
  box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2); /* 悬浮时加深阴影 */
}

.section_5 {
  position: relative;
  padding: 0;
  height: 200px;
  width: 100%; /* 确保宽度100% */
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  border-radius: 8px 8px 0 0;
  background-color: #f5f7fa; /* 添加背景色，当图片不存在时显示 */
}

.text-wrapper {
  display: flex; /* 启用 flex 布局 */
  flex-direction: column; /* 垂直排列子元素 */
  align-items: flex-start; /* 子元素在水平方向靠左对齐 */
  padding: 6px 3px 6px; /* 添加内边距 */
  background-color: #d9d9d999; /* 背景色 */
  border-radius: 12px; /* 圆角 */
  width: 173.5px; /* 固定宽度 */
  margin-left: 12px; /* 左侧间距 */
}

.font_3 {
  color: white;
  font-size: 18px;
  font-weight: bold;
  letter-spacing: 1px;
}

.section_6 {
  padding: 16px;
  background-color: #ffffff;
  border-radius: 0 0 8px 8px;
}

.font_4 {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  flex: 1;
  margin-right: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.text_9 {
  margin-left: 2px;
}

.text-wrapper_2 {
  display: flex; /* 启用 flex 布局 */
  justify-content: center; /* 子元素水平居中 */
  align-items: center; /* 子元素垂直居中 */
  padding: 10px 0 10px;
  background-color: #d9d9d9;
  margin-top: 10px;
  margin-bottom: 0px;
  border-radius: 12px;
  width: 55.5px;
  height: auto; /* 如果需要固定高度，可改为具体值 */
}

.tag_span {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 12px;
}

.font_5 {
  font-size: 12px;
  color: #666;
  background-color: #f5f7fa;
  padding: 4px 8px;
  border-radius: 4px;
}

.font_5:hover {
  background-color: #e6e8eb;
  /*transform: translateY(-1px);*/
}

/* 添加信息覆盖层样式 */
.info-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  padding: 12px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.price-tag {
  background-color: rgba(230, 103, 33, 0.9);
  padding: 6px 12px;
  border-radius: 8px;
}

.people-tag {
  background-color: rgba(0, 0, 0, 0.6);
  padding: 6px 12px;
  border-radius: 8px;
  color: white;
  display: flex;
  align-items: center;
  gap: 4px;
}

.people-tag i {
  font-size: 14px;
}

/* 修改标题行样式 */
.title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.date-tag {
  font-size: 12px;
  color: #666;
  background-color: #f5f7fa;
  padding: 2px 8px;
  border-radius: 4px;
}

/* 添加截止时间样式 */
.deadline-info {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #e6a23c;
  margin-bottom: 8px;
}

.deadline-info i {
  font-size: 14px;
}

/* 任务详细信息样式 */
.job-details {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f2f5;
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #606266;
}

.detail-item i {
  font-size: 14px;
  color: #909399;
}

/* AI标签样式 */
.ai-tag {
  margin-left: 4px;
  /* transform: scale(0.8); */
  transform-origin: left center;
}

/* 调整图标样式 */
.el-icon-cpu {
  color: #409eff;
}

.el-icon-s-operation {
  color: #67c23a;
}

/* 发帖时间样式 */
.post-time {
  margin-left: 8px;
  color: #909399;
  font-size: 12px;
}

/* 添加删除按钮样式 */
.delete-button,
.delete-job-button,
.terminate-button,
.edit-button {
  position: absolute;
  top: 12px;
  width: 32px;
  height: 32px;
  background-color: rgba(0, 0, 0);
  cursor: pointer;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.delete-button {
  right: 12px;
}

.terminate-button {
  right: 52px;
}

.edit-button {
  right: 92px;
}

.delete-job-button{
  right: 92px;
}

.delete-button:hover,
.delete-job-button:hover,
.terminate-button:hover,
.edit-button:hover {
  background-color: rgba(0, 0, 0, 0.8);
  transform: scale(1.1);
}

.edit-button {
  position: absolute;
  top: 12px;
  right: 15px;
  width: 32px;
  height: 32px;
  background-color: rgba(0, 0, 0, 0.6);
  cursor: pointer;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  color: white;
}

.delete-button i,
.delete-job-button i,
.terminate-button i,
.edit-button i {
  color: #fff;
  font-size: 16px;
}

.terminate-button i {
  color: #fff;
  font-size: 16px;
}

.edit-button i {
  color: #fff;
}

.delete-job-button i {
  color: #fff;
}

.delete-button {
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.delete-button i {
  color: white;
  font-size: 16px;
}

.delete-button:hover {
  background-color: rgba(245, 108, 108, 0.9);
  transform: scale(1.1);
}

/* 点赞样式 */
.like-item {
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  margin-left: auto; /* 将点赞放在最右侧 */
}

.like-item:hover {
  transform: scale(1.1);
}

.like-icon {
  font-size: 16px;
  color: #909399;
  margin-right: 4px;
  transition: all 0.3s ease;
  transform: scale(1);
}

.like-icon.liked {
  color: #ff4949;
  transform: scale(1.2);
}

.like-count {
  font-size: 14px;
  color: #606266;
}

.like-item:hover .like-icon:not(.liked) {
  color: #ff4949;
  opacity: 0.7;
}
</style>
